//
//  TTRefreshController.swift
//  TTWeibo
//
//  Created by 陶宏路 on 16/7/25.
//  Copyright © 2016年 陶路路. All rights reserved.
//

import UIKit

enum RefreshState:Int{
    
    case Nomal = 0
    case Pulling = 1
    case Refresh = 2
}

let RefreshControl: CGFloat = 50

class TTRefreshController: UIControl {
    
    
    var refreshState:RefreshState = .Nomal

    override init(frame: CGRect) {
        
        super.init(frame: CGRectMake(0, -50, SCREENW, 50))
        
        backgroundColor = UIColor.orangeColor()
    
        setUpUI()
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setUpUI(){
        
        addSubview(textLable);
        
        textLable.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self)
        }
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let scrollView:UIScrollView = newSuperview as? UIScrollView{
            
            self.scrollView = scrollView
            
            self.scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        getStatueWithContenOffset(self.scrollView.contentOffset.y)
        
    }
    
    
    func getStatueWithContenOffset(contentOffsetY: CGFloat){
    
        let contentInsetTop = self.scrollView.contentInset.top
        
        // 代表用户正在拖动
        if self.scrollView.dragging {
            if contentOffsetY > -contentInsetTop - RefreshControl && refreshState == .Pulling{
                refreshState = .Nomal
            }else if contentOffsetY <= -contentInsetTop - RefreshControl && refreshState == .Nomal{
                refreshState = .Pulling
            }
            
        }else {
            // 代表用户松手了
            if refreshState == .Pulling {
                refreshState = .Refresh
                
                print("刷新")
            }
            
        }

    }
    

    lazy var scrollView:UIScrollView = UIScrollView()
    
    lazy var textLable:UILabel = {
       let text = UILabel()
        text.font = UIFont.systemFontOfSize(18)
        text.text = "正常"
        text.textColor = UIColor.whiteColor()
        return text
    }()
    
    lazy var image:UIImageView = {
       let img = UIImageView()
        img.image = UIImage(named: "tableview_pull_refresh")
        return img
    }()
    
    deinit{
        
        self.scrollView.removeObserver(self, forKeyPath: "contentOffset")
    }
}
